<?php

namespace Addons\HomeControl;
use Common\Controller\Addon;

/**
 * 前台首页内容控制插件
 * @author Tealun
 */

    class HomeControlAddon extends Addon{

        public $info = array(
            'name'=>'HomeControl',
            'title'=>'前台内容控制插件',
            'description'=>'基于bootstrap 3.2.0实现的前台首页内容控制插件，需要Admin板块控制器和视图配合，及创建菜单和权限',
            'status'=>1,
            'author'=>'Tealun Du',
            'version'=>'0.2'
        );
        private $viewDir = 'View/';

        public function install(){
            return true;
        }

        public function uninstall(){
            return true;
        }

        private function getTheme(){
            $config = $this->getConfig();
            return $config['theme'];
        }

        //实现的homeLogo钩子方法
		public function homeLogo(){
			$logo = F('Tchat/homeLogo');
            $logo && $this->assign('logo',$logo);
			$this->display($this->viewDir.$this->getTheme().'/logo');
		}
		
		 //实现的homeSlide钩子方法
		public function homeSlide(){
			$slideList = F('Tchat/homeSlide'); //获取幻灯片设置的内容
            //赋值特色内容条目
            foreach ($slideList['items'] as $key => $value) {
                switch ($value['type']) {
                    case 'diy':
                        $slideList['items'][$key]['cover'] = get_cover($value['cover_id'], 'path');
                        $slideList['items'][$key]['alt'] = $value['title'];
                        break;
                    default:
                        $slideList['items'][$key] = $this->findItemInfo($value['type'], $value['id']);
                        //fixme 这里有问题，应该是自定义的cover_id和条目的cover_id重复了，上面这句会把自定义的cover_id覆盖掉
                        if(!empty($value['cover_id'])){
                            $slideList['items'][$key]['cover'] = get_cover($value['cover_id'], 'path');
                        }
                        break;
                }
            }
			$this->assign('slideItems',$slideList['items']);
			$this->display($this->viewDir.$this->getTheme().'/slide');
        }

        /**
         * 实现homeLists钩子方法
         */
        public function homeLists($data=array()){
            $type=$data['type']?$data['type']:'category';//没有传入类型则默认分类
            $limit = $data['limit']?$data['limit']:4; //如果没有传入限制查询条数，则只查找4条
            $id = $data['id'];
            $tmp = $data['tmp']?'/homelists/'.$data['tmp']:'/homeLists';
            switch($type){
                case 'article':
                    if(is_numeric($id)){//只有一个文章ID的情况下找出这个文章的内容
                        $articleLists = $this->findItemInfo($type,$id);
                        $articleLists['url'] = U('Home/Article/detail?id='.$articleLists['id']);
                        $this->assign('singleArticle',true);//定义单个文章变量，以编写不同输出模版
                        $tmp = '/homelists/single';
                    }else{//传入多个ID，则找出每一文章的详情组成数组
                        $ids = str2arr($id);
                        $articleLists = array();
                        foreach ($ids as $k=>$v){
                            $articleLists[$v] = $this->findItemInfo($type,$v);
                        }
                        foreach($articleLists as $k=> $article){
                            $articleLists[$k]['url']=U('Home/Article/detail?id='.$article['id']);
                        }
                    }
                    break;
                case 'album':
                    if(is_numeric($id)){//判断是否是数字ID
                        //查找指定分类及子分类的文章列表
                        $articleLists = M('TchatPicture')
                            ->where(array(
                                'album_id'=>array('eq',$id)
                            ))
                            ->field('id,pic_id,title,description')
                            ->order('id desc')
                            ->limit($limit)
                            ->select();
                        foreach($articleLists as $k=> $article){
                            $articleLists[$k]['cover_id']=$article['pic_id'];
                            $articleLists[$k]['url']=U('Home/Album/detail?id='.$id);
                            unset($articleLists[$k]['pic_id']);
                        }
                    }
                    break;
                case 'albumCategory':
                    if(!is_numeric($id)){//判断是否是数字ID
                        //传入不是数字ID的时候，按标识名来查找ID
                        $id =  M('AlbumCategory')->where(array('name'=>$id))->getField('id');
                    }
                    //查找指定分类及子分类的文章列表
                    $articleLists = M('TchatAlbum')
                        ->where(array(
                            'status' => array('eq', 1),
                            'cat_id'=>array('eq',$id)
                        ))
                        ->field('id,title,description,cover_id')
                        ->order('id desc')
                        ->limit($limit)
                        ->select();
                    foreach($articleLists as $k=> $article){
                        $articleLists[$k]['index_pic']=$article['cover_id'];
                        $articleLists[$k]['url']=U('Home/Album/detail?id='.$article['id']);
                    }
                    break;
                default: //默认是分类
                    if(!is_numeric($id)){//判断是否是数字ID
                        //传入不是数字ID的时候，按标识名来查找ID
                        $id =  M('Category')->where(array('name'=>$id))->getField('id');
                    }
                    //查找指定分类下有无子分类，并组成相应的分类数组
                    $categories = M('Category')->where('pid = '.$id)->getField('id',true);
                    if($categories){
                        array_push($categories,$id);
                    }else{
                        $categories = array($id);
                    }

                    //查找指定分类及子分类的文章列表
                    $articleLists = M('Document')
                        ->where(array(
                            'status' => array('eq', 1),
                            'category_id'=>array('in',$categories)
                        ))
                        ->field('id,title,description,cover_id,index_pic')
                        ->order('id desc')
                        ->limit($limit)
                        ->select();
                    foreach($articleLists as $k=> $article){
                        $articleLists[$k]['url']=U('Home/Article/detail?id='.$article['id']);
                    }

            }
            $this->assign('addons_articleLists',$articleLists);
            $this->display($this->viewDir.$this->getTheme().$tmp);
        }

		/**
		 * 实现的homeFeature钩子方法
		 * 此前台控制首页中特色栏目导航
		 */
		public function homeFeature($position=''){
	
			//读取缓存中的特色内容
			$feature = F('Tchat/homeFeature');
			
			//赋值特色内容条目

            foreach ($feature['items'] as $key => $value) {
                switch ($value['type']) {
                    case 'diy':
                        $feature['items'][$key]['cover'] = get_cover($value['cover_id'], 'path');
                        $feature['items'][$key]['alt'] = $value['title'];
                        break;
                    default:
                        $feature['items'][$key] = $this->findItemInfo($value['type'], $value['id']);
                        break;
                }
            }

            $this->assign('featureItems',$feature['items']);

			//赋值特色内容板块标题
			if($feature['title']){
				$this->assign('featureTitle',$feature['title']);
			}
			
			//赋值查看更多转向URL
			if($feature['moreLinkUrl']){
				$this->assign('featureMoreLinkUrl',$feature['moreLinkUrl']);
			}
			if(empty($position)){
                $this->display($this->viewDir.$this->getTheme().'/feature');
            }else{
                $this->display($this->viewDir.$this->getTheme().'/featureIcon');
            }

		}
		
		//实现的banner钩子方法
		public function banner($type='Slide'){
			$banners = F('Tchat/homeBanner');
            //var_dump($banners);
            $this->assign('type',$type);
			$this->assign('addons_banners',$banners);
			$this->display($this->viewDir.$this->getTheme().'/banner');
		}

		//实现的documentDetailAfter钩子方法
		public function documentDetailBefore(){
			$beforeArticle = F('Tchat/homeBeforeArticle');
			$this->assign('addons_beforeArticle',$beforeArticle);
			$this->display($this->viewDir.$this->getTheme().'/beforeArticle');
		}
		
		//实现的documentDetailAfter钩子方法
		public function documentDetailAfter(){
			$afterArticle = F('Tchat/homeAfterArticle');
			$this->assign('addons_afterArticle',$afterArticle);
			$this->display($this->viewDir.$this->getTheme().'/afterArticle');
		}

		private function findItemInfo($type=' ',$id=' '){
					
		switch ($type) {
				case 'category': //内容分类类型
					$category = M('category')->find($id);
				
					$info['type'] = $type;
					$info['id']=$id;
                    if($category['pid'] == 0){//判断是否属于子分类，子分类用list,父级分类用index
                        $info['url'] = U('Home/Article/index',array('category'=>$id));
                    }else{
                        $info['url'] = U('Home/Article/lists',array('category'=>$id));
                    }
					$info['cover_id'] = $category['cover_id'];
					$info['icon_id'] = $category['icon'];
					$info['cover'] = get_cover($category['cover_id'],'path');
                    $info['icon'] = get_cover($category['icon'],'path');
					$info['title']=$category['title'];
					$info['alt']=$category['title'];
					$info['description']=$this->rebuildItemDescription($category['description']);
                    $info['articles']=$this->findArticles($id);
					unset($category);
					break;
					
				case 'article'://文章及产品类型
					
					$article = D('Document')->detail($id); //获取条目内容详情
					
					$info['type'] = $type;
					$info['id']=$id;
					$info['url'] = U('/Home/article/detail',array('id'=>$id));
					$info['cover_id'] = $article['cover_id'];
					$info['icon_id'] = $article['index_pic'];
					$info['cover'] = get_cover($article['cover_id'],'path');
                    $info['icon'] = get_cover($article['index_pic'],'path');
					$info['title']=$article['title'];
					$info['alt']=$article['title'];
					$info['description']=$article['description'];
					
					unset($article); //删除article的变量
					break;
					
				default:
					
					break;
			}
					return $info;//返回整合后的条目内容
		}

        /**
         * 查找分类下的文章列表
         * @param $category_id
         * @return mixed
         */
        private function findArticles($category_id){
            //查找指定分类下有无子分类，并组成相应的分类数组
            $categories = M('Category')->where('pid = '.$category_id)->getField('id',true);
            if($categories){
                array_push($categories,$category);
            }else{
                $categories = array($category_id);
            }
            //查找制定分类及子分类的文章列表
            $articleLists = M('Document')
                ->where(array('status' => array('eq', 1), 'category_id'=>array('in',$categories)))
                ->field('id,title,description,cover_id,index_pic')
                ->order('create_time desc')
                ->limit(4)
                ->select();
            return $articleLists;
        }

        private function rebuildItemDescription($description){
            return preg_replace('/\r\n/','<br />',$description);
        }

    }